import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import {allRouter,baseRouter,errorPage,indexHb,indexDefault}  from './router';
import store from './vuex/store';
import Util from './libs/util';
import App from './app.vue';
import 'iview/dist/styles/iview.css';
import './my-theme/index.less';
import './my-theme/table.css';
import './my-theme/form.css';
import './my-theme/yang.css';
import echarts from 'echarts';
import VueAMap from 'vue-amap';
import tinymce from 'tinymce';
import VueClipboard from 'vue-clipboard2'
import { getPermission , getInfo } from './api/common'
import { util } from 'node-forge';
import VueEcho from 'vue-echo';

//Vue.use(VueEcho,{})
Vue.use(VueEcho, {
    broadcaster: 'socket.io',
    //key: '2806278dc56ea4e37140a54b76202c93',
    host: SOCKET_URL,
    namespace: 'App.Events',
    secure: true,
});

// import VueSocketio from 'vue-socket.io';
// import socketio from 'socket.io-client';
// Vue.use(VueSocketio, socketio('http://192.168.0.88:6001'));






Vue.use(VueAMap);
// Vue.use(tinymce);
Vue.use(VueClipboard)
VueAMap.initAMapApiLoader({
  key: 'e23776ac127541db6f50f86e55fbfa55',
  plugin: ['Scale', 'OverView', 'ToolBar', 'MapType','PlaceSearch','Geolocation']
});

Vue.prototype.$isShow = function (action) {
    let canshow = false 
    let _obj = this.ACTIONS
    if(_obj[action]){
        canshow = true
    }
    return canshow
}



Vue.prototype.$echarts = echarts 
Vue.use(VueRouter);

Vue.use(iView);

let newRouters = [];
//console.log(allRouter)
newRouters = newRouters.concat(baseRouter)

// 路由配置
const RouterConfig = {
    // mode: 'history', //控制路由是否有#
    routes: newRouters     //newRouters
};
const router = new VueRouter(RouterConfig);

const whiteList = ['/login/'];
router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);
    store.dispatch('setRouterHome', to.name);
    store.dispatch('updataTitle', {'title':to.meta.title,'des':to.meta.des});
    console.log(to) 
    if (sessionStorage.getItem('id')&&sessionStorage.getItem('token')) {
        if (to.path.indexOf(whiteList) !== -1) {
            next('/index');
            return
        }
        console.log('1')
        if(JSON.stringify(store.state.operation) == "{}") {
            console.log('2')
            if(!store.state.user.id){
                new Promise((resolve, reject) => {
                    let _params = {
                        'yid': sessionStorage.getItem('id'),
                    }
                    getInfo(_params).then(response => {
                        if(response.data.err == 0){
                            let _value = {
                                'id': response.data.data.id,
                                'name': response.data.data.name,
                                'avator': response.data.data.avatar,
                                'user_type': response.data.data.user_type,
                                'account_type':response.data.data.account_type,
                                'org_mid':response.data.data.org_mid,
                                'eid':response.data.data.eid,
                                'child_org_mids':response.data.data.child_org_mids,
                                'filter_org':response.data.data.filter_org
                            }
                            store.dispatch('GetInfo',_value)
                            Vue.prototype.$accountType = {
                                'account_type':response.data.data.account_type,
                                'org_mid':response.data.data.org_mid,
                                'eid':response.data.data.eid,
                                'child_org_mids':response.data.data.child_org_mids,
                                'filter_org':response.data.data.filter_org
                            }
                        }
                        resolve(response);
                    }).catch(error => {
                        reject(error);
                    });
                });
                
            }
            let _params = {
                'yid': sessionStorage.getItem('id'),
            }
            new Promise((resolve, reject) => {
                getPermission(_params).then(response => {
                    if(response.data.err == 0){ 
                        console.log(3)     
                        let operation = response.data.data.operation
                        let actions = response.data.data.actions
                        //console.log(operation)
                        let toggle = {}
                        toggle = Object.assign({},operation)
                        store.dispatch('GetPermission',toggle)
                        let actions_obj = Util.actions2Object(actions)
                        // console.log(actions_obj,"actions")
                        Vue.prototype.ACTIONS = actions_obj
                        store.dispatch('GetActions',actions_obj)
                        // console.log(store,"store")
                        let newRouter = Util.transformRouter(allRouter,operation)
                        //不同公司不同首页

                        //注入路由
                        let _otherRouter  = null
                        if(sessionStorage.getItem('id') == 47){
                            _otherRouter = [indexHb,errorPage] 
                        }else{
                            _otherRouter = [indexDefault,errorPage] 
                        }
                        newRouter.unshift(..._otherRouter)
                        console.log(newRouter)
                        router.addRoutes(newRouter.concat([{
                            path: '*',
                            redirect: '/404'
                        }]));
                        if(to.path =='/index'){
                            
                            next('/')
                            
                            
                        }else{
                            console.log(to)
                            next(to.path)
                        }
                        //next();
                        //next('/');
                        
                    } else {
                        // sessionStorage.removeItem('id');
                        // location.reload();
                    }
                    resolve(response);
                }).catch(error => {
                    reject(error);
                });
            });
        }else{
            if(!store.state.user.id){
                new Promise((resolve, reject) => {
                    let _params = {
                        'yid': sessionStorage.getItem('id'),
                    }
                    getInfo(_params).then(response => {
                        if(response.data.err == 0){
                            let _value = {
                                'id': response.data.data.id,
                                'name': response.data.data.name,
                                'avator': response.data.data.avatar,
                                'user_type': response.data.data.user_type,
                                'account_type':response.data.data.account_type,
                                'org_mid':response.data.data.org_mid,
                                'eid':response.data.data.eid,
                                'child_org_mids':response.data.data.child_org_mids,
                                'filter_org':response.data.data.filter_org
                            }
                            store.dispatch('GetInfo',_value)
                            Vue.prototype.$accountType = {
                                'account_type':response.data.data.account_type,
                                'org_mid':response.data.data.org_mid,
                                'eid':response.data.data.eid,
                                'child_org_mids':response.data.data.child_org_mids,
                                'filter_org':response.data.data.filter_org
                            }
                        }
                        resolve(response);
                    }).catch(error => {
                        reject(error);
                    });
                });
                
            }
            next();
        }
        
         
        
        // if(JSON.stringify(store.state.toggle) == "{}") {
        //     store.dispatch('GetPermission')
        // }
        
    } else {
        //alert(to.path.indexOf(whiteList))
        var v = window.document.cookie.match('(^|;) ?id=([^;]*)(;|$)');
        var _id = v ? v[2] : null;
        if (to.path.indexOf(whiteList) !== -1) {
            var _arr = to.path.split('/login/')
            if(_arr[1] == ''){
                if(_id){
                    next('/login/'+_id);
                }else{
                    next('/login/0');
                } 
            }else{
                document.cookie = "id ="+_arr[1]+';path=/;'
                next()
            }           
        } else {            
            if(_id){
                next('/login/'+_id);
            }else{
                next('/login/0');
            }                       
            
        }
    }
    
});

router.afterEach(() => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});

new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    // created () {
    //     let tagsList = [];
    //     Routers.map((item) => {
    //         if(item.children){
    //             if (item.children.length <= 1) {
    //                 tagsList.push(item.children[0]);
    //             } else {
    //                 tagsList.push(...item.children);
    //             }
    //         }            
    //     });
    //     this.$store.commit('setTagsList', tagsList);
    // }
});